import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.net.PortUnreachableException;
import java.net.SocketException;
import java.nio.channels.IllegalBlockingModeException;
import java.util.concurrent.TimeUnit;

public class Sender implements Runnable {

	private Router router;

	public Sender(Router router) {
		this.router = router;
	}

	private int getPort(Neighbor neighbor) {
		return Integer.parseInt(router.getRouters().get(neighbor.getId())
				.getPort());
	}

	private String getIpAddress(Neighbor neighbor) {
		return router.getRouters().get(neighbor.getId()).getAddress();
	}

	private void sendMsg(Neighbor neighbor) {
			int receiverPort = getPort(neighbor);
			InetSocketAddress receiverIp = new InetSocketAddress(getIpAddress(neighbor), receiverPort);
			byte[] buffer = router.getMessage(neighbor.getId()).getBytes();

			DatagramPacket sendDataPacket = null;
			try {
				sendDataPacket = new DatagramPacket(buffer, buffer.length,receiverIp);
			} catch (SocketException e1) {
				router.setInativeNeighbor(neighbor);
				return;
			}

			try {
				router.getSocket().send(sendDataPacket);
			} catch (SecurityException e) {
				router.setInativeNeighbor(neighbor);
			} catch (PortUnreachableException e) {
				router.setInativeNeighbor(neighbor);
			} catch (IllegalBlockingModeException e) {
				router.setInativeNeighbor(neighbor);
			} catch (IOException e) {
				router.setInativeNeighbor(neighbor);
			}

	}

	public void run() {
		while (true) {
			for (Neighbor no : router.getNeighbors()){

				if (no.isNeighbor()) {
					sendMsg(no);
				}
				
				try {
					TimeUnit.MILLISECONDS.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
					System.exit(1);
				}
			}
		}
	}

}
